package com.ruoyi.framework.aspectj;

import java.lang.reflect.Method;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.SearchLog;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysOperLog;

/**
 * 操作日志记录处理
 * 
 * @author ruoyi
 */
@Aspect
@Component
public class LogAspect
{
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    private final ThreadLocal<Long> threadLocal=new ThreadLocal<>();

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IDynamicSearchService dynamicSearchService;


    /**
     * 进入到方法前
     * @param joinPoint
     * @param controllerLog
     */
    @Before("@annotation(controllerLog)")
    public void beforePointcut(JoinPoint joinPoint, Log controllerLog) {
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        Method method=methodSignature.getMethod();
        Log annotation = method.getAnnotation(Log.class);
        if (annotation!=null){
            threadLocal.set(System.currentTimeMillis());
        }
    }

    /**
     * 执行方法后
     * @param joinPoint
     * @param controllerLog
     */
    @After("@annotation(controllerLog)")
    public void afterPointcut(JoinPoint joinPoint, Log controllerLog) {

    }




    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult)
    {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     * 
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
    {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
    {
        try{
            // 获取当前的用户
            LoginUser loginUser = null;
            try{
                loginUser = SecurityUtils.getLoginUser();
            }catch (Exception eu){
                System.out.println("获取用户信息失败");
            }
            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            operLog.setTimeConsuming((System.currentTimeMillis() - threadLocal.get())+"");
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            if (loginUser != null){
                operLog.setOperName(loginUser.getUsername());
            }
            if (e != null){
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            String saveType = controllerLog.saveType().name();
            if("SQL".equals(saveType)){
                // 保存数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
            }else{
                String operParam = operLog.getOperParam();
                Map<String, Object> queryMap = new HashMap<>();
                try{
                    //body请求
                    queryMap = JSONObject.parseObject(operParam);
                }catch (Exception ep){
                    queryMap = GetUrlParam.queryStrToMap(operParam);
                }
                if(queryMap==null){
                    queryMap = new HashMap<>();
                }
                String name = controllerLog.businessType().name();
                operLog.setBusinessTypeStr(controllerLog.businessType().name());
                Map<String, String> timeMap = new HashMap<>();
                timeMap.put("y", DateUtils.dateTimeNow("yyyy"));
                timeMap.put("ym", DateUtils.dateTimeNow("yyyyMM"));
                timeMap.put("ymd", DateUtils.dateTimeNow("yyyyMMdd"));
                timeMap.put("ymdh", DateUtils.dateTimeNow("yyyyMMddHH"));
                timeMap.put("ymdhm", DateUtils.dateTimeNow("yyyyMMddHHmm"));
                timeMap.put("ymdhms", DateUtils.dateTimeNow("yyyyMMddHHmmss"));
                operLog.setCreateTimeMap(timeMap);
                operLog.setCreateTimeStr(DateUtils.getTime());
                if("RTA".equals(name)){
                    if("/ownHWApi/rta".equals(operLog.getOperUrl()) || "/ownZijieRtaApi/youku_rta".equals(operLog.getOperUrl())){
                        operLog.setDmpid(queryMap.get("reqId")+"");
                        String params =  ServletUtils.getRequest().getQueryString();
                        Map<String, Object> queryStrToMap = GetUrlParam.queryStrToMap(params);
                        queryMap.putAll(queryStrToMap);
                    }else if("/ownBaiDuApi/rta".equals(operLog.getOperUrl())){
                        String redisKey = operLog.getDmpid() + "_Cache";
                        if(redisCache.exists(redisKey)){
                            Map<String, Object> cacheMap = redisCache.getCacheMap(redisKey);
                            operLog.setDmpid(cacheMap.get("dmpid")+"");
                        }
                    }else{
                        operLog.setDmpid(queryMap.get("dmpid")+"");
                    }
                }else if("ESCALATION".equals(name)){
                    if("/ownOcpxXinYiApi/send".equals(operLog.getOperUrl())){
                        operLog.setDmpid(queryMap.get("ad_id")+"");

                        queryMap.put("channelId", queryMap.get("ad_unit_id")+"");
                        queryMap.put("dmpid", queryMap.get("ad_id")+"");
                    }else{
                        operLog.setDmpid(queryMap.get("dmpid")+"");
                    }
                }else{
                    //回调
                    //http://127.0.0.1:9185/ownApi/callback/channelId/hmbb1234/29453bf393d730193fa1b0e57ac80d9ca591350df34bbd4639d3655866a9f2d28e59d100992aad06223f305b05227710
                    String operUrl = operLog.getOperUrl();
                    String getDmpidUrl = operUrl.substring(0, operUrl.lastIndexOf("/"));
                    String dmpid = getDmpidUrl.substring(getDmpidUrl.lastIndexOf("/")+1);

                    String dyc = operUrl.substring(0, operUrl.lastIndexOf("/"));
                    String getChannelIdUrl = dyc.substring(0, dyc.lastIndexOf("/"));
                    String channelId = getChannelIdUrl.substring(getChannelIdUrl.lastIndexOf("/")+1);
                    queryMap.put("channelId", channelId);
                    queryMap.put("dmpid", dmpid);

                    operLog.setDmpid(dmpid);
                }

                String redisKey = operLog.getDmpid() + "_Cache";
                if(redisCache.exists(redisKey)){
                    Map<String, Object> cacheMap = redisCache.getCacheMap(redisKey);
                    queryMap.putAll(cacheMap);
                   redisCache.deleteObject(redisKey);
                }

                //用于配置错误渠道，对渠道进行转发的操作
                String redisMapping = operLog.getDmpid() + "_ChannelIDMapping";
                if(redisCache.exists(redisMapping)){
                    String channelId = redisCache.getCacheObject(redisMapping) + "";
                    queryMap.put("channelId", channelId);
                    redisCache.deleteObject(redisMapping);
                }

                //抖音渠道如果是点击记录，判断是否已经上报过
                if("ESCALATION".equals(name) && "/ownDouYinApi/send".equals(operLog.getOperUrl())){
                    Boolean dmpIdBool = getDmpId(queryMap.get("channelId") + "", operLog.getDmpid());
                    if (dmpIdBool) {
                        log.info("dmpid[{}]已经上报过，不再上报和记录", operLog.getDmpid());
                        return;
                    }
                }

                try{
                    String timeConsuming = operLog.getTimeConsuming();
                    if(StringUtils.isNotBlank(timeConsuming)){
                        queryMap.put("timeConsuming", Double.parseDouble(timeConsuming));
                    }

                    if(queryMap.containsKey("reportTimeConsumption")){
                        queryMap.put("reportTimeConsumption", Double.parseDouble(queryMap.get("reportTimeConsumption")+""));
                    }

                }catch (Exception e1) {
                    log.error("时间转换异常", e1);
                }


                operLog.setParams(queryMap);
                // 保存ES
                String index = controllerLog.esIndex();
                if("RTA".equals(name) && index.startsWith("youdao_log")){
                    index = index + "_rta_" + DateUtils.dateTime();
                }
                AsyncManager.me().execute(AsyncFactory.recordOperEs(operLog, index, ""));
            }
        }catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    //用于判断今日内dmpid是否已经上报过
    private Boolean getDmpId(String channelId, String dmpid) {
        String date = DateUtils.getDate() + " 00:00:00";
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("businessTypeStr.keyword", "ESCALATION"));
        boolQueryBuilder.must(QueryBuilders.termQuery("params.channelId.keyword", channelId));
        boolQueryBuilder.must(QueryBuilders.termQuery("dmpid.keyword", dmpid));
        boolQueryBuilder.must(new RangeQueryBuilder("createTimeStr.keyword").gte(date).format("yyyy-MM-dd HH:mm:ss"));
        Long youdaoLog = dynamicSearchService.searchCount("youdao_log", null, boolQueryBuilder);
        return youdaoLog > 0;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * 
     * @param log 日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception
    {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData())
        {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
        {
//            operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
            operLog.setJsonResult(JSON.toJSONString(jsonResult));
        }
    }

    /**
     * 获取请求的参数，放到log中
     * 
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception
    {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
        {
            String params = argsArrayToString(joinPoint.getArgs());
            Map<String, Object> bodyMap = new HashMap<>();
            try{
                bodyMap = JSONObject.parseObject(params, Map.class);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            String queryParams =  ServletUtils.getRequest().getQueryString();
            Map<String, Object> queryToMap = GetUrlParam.queryStrToMap(queryParams);

            Map<String, Object> allParams = new HashMap<>();
            if(bodyMap != null){
                allParams.putAll(bodyMap);
            }

            for (String key : queryToMap.keySet()) {
                if(allParams.containsKey(key)){
                    //以body参数为主
                }else{
                    allParams.put(key, queryToMap.get(key));
                }
            }
            operLog.setOperParam(JSONObject.toJSONString(allParams));
        }
        else if (HttpMethod.GET.name().equals(requestMethod))
        {
            String params =  ServletUtils.getRequest().getQueryString();
            operLog.setOperParam(params);
        }else
        {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(paramsMap.toString());
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (Object o : paramsArray)
            {
                if (StringUtils.isNotNull(o) && !isFilterObject(o))
                {
                    try
                    {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     * 
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o)
    {
        Class<?> clazz = o.getClass();
        if (clazz.isArray())
        {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        }
        else if (Collection.class.isAssignableFrom(clazz))
        {
            Collection collection = (Collection) o;
            for (Object value : collection)
            {
                return value instanceof MultipartFile;
            }
        }
        else if (Map.class.isAssignableFrom(clazz))
        {
            Map map = (Map) o;
            for (Object value : map.entrySet())
            {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
